package com.shuhe.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.shuhe.common.HttpClient;
import com.shuhe.domain.api.ApiResponseBody;
import com.shuhe.metastore.MetaMysql;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import static com.shuhe.common.CommonFunction.*;
import static com.shuhe.handler.ServiceDetail.decryptToken;

public class ServiceBusHandler extends HttpServlet {

    private static Logger logger = Logger.getLogger(ServiceBusHandler.class);


    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp = setResponse(resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection metaConn = null;
        String id = getUUID();
        String userName = "";
        try {
            SimpleDateFormat nyr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String req_time = nyr.format(new Date());
            req.setCharacterEncoding("UTF-8");
            resp = setResponse(resp);
            String bodyStr = readAsChars(req);
            String tokenKey = req.getHeader("sh_token");
            userName = decryptToken(tokenKey);
            String sh_service_code = req.getHeader("sh_service_code");
            String sql = "select api_server_addr from service_register a, service_audit b where a.id = b.reg_id " +
                    "and a.service_code = '" + sh_service_code + "' and b.user_name = '" + userName + "'"
                    + " and b.run_statu = '0'";
            metaConn = MetaMysql.connect();
            ResultSet rs = MetaMysql.querySql(metaConn, sql);
            ArrayList<String> tableNames = new ArrayList();
            String api_server_addr = "";
            if (rs.next()) {
                api_server_addr = rs.getString("api_server_addr");
            }
            if (api_server_addr.length() == 0) {
                makeFailBody("用户没有访问服务的权限", resp, metaConn, id, userName);
                return;
            }
            Map<String, String> heads = HttpClient.getAllHeaders(req);
            logger.info(api_server_addr);
            String respBody = HttpClient.postHttp(api_server_addr, bodyStr, heads).replace("\"null\"", "null");
            int resLen = 499;
            String res_body = respBody.substring(0, respBody.length() > resLen ? resLen : respBody.length());
            String rep_body = bodyStr.substring(0, bodyStr.length() > resLen ? resLen : bodyStr.length());
            res_body = res_body.replace("'", "''");
            rep_body = rep_body.replace("'", "''");
            //日志
            sql = "insert into service_log(\n" +
                    "id,user_name,req_time,service_code, res_time, res_body, res_status, req_body)\n" +
                    "values('" + id + "','" +
                    userName + "','" + req_time + "','" + sh_service_code + "','" + nyr.format(new Date()) + "','"
                    + res_body + "','success','" + rep_body + "')";
            MetaMysql.execSql(metaConn, sql);

            // 接口返回，原值null原样返回
            JSONObject jsonObject = JSON.parseObject(respBody);
            String jsonString = JSON.toJSONString(jsonObject, SerializerFeature.WriteMapNullValue);

            resp.getWriter().print(jsonString);
        } catch (Exception ex) {
            try {
                int exLen = ex.getMessage().length();
                if (exLen > 499) {
                    exLen = 499;
                }
                makeFailBody(ex.getMessage().substring(0, exLen), resp, metaConn, id, userName);
            } catch (Exception ex1) {

            }
            ex.printStackTrace();
        } finally {
            closeDb(metaConn);
        }
    }

    private void makeFailBody(String msg, HttpServletResponse resp, Connection metaConn, String id, String userName) throws Exception {
        ApiResponseBody body = new ApiResponseBody();
        body.setStatus("201");
        body.setMsg(msg);
        SimpleDateFormat nyr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String res_time = nyr.format(new Date());
        String sql =
                "insert into service_log(res_time, res_status, err_detail, id, user_name) values('"
                        + res_time + "','fail','失败：" + msg + "','" + id + "','" + userName + "')";
        MetaMysql.execSql(metaConn, sql);
        resp.getWriter().write(JSONObject.toJSONString(body));
    }
}
